<template>
  <!-- 只有选中 patient 时才显示整块内容 -->
  <div v-if="localPatient.id" class="diagnosis-confirm p-4 bg-white space-y-4">
    <!-- 患者信息 -->
    <el-card>
      <div class="flex space-x-4">
        <div>病历号：<strong>{{ localPatient.casenumber }}</strong></div>
        <div>姓名：<strong>{{ localPatient.realname }}</strong></div>
        <div>性别：<strong>{{ localPatient.sex }}</strong></div>
        <div>年龄：<strong>{{ localPatient.age }}</strong></div>
      </div>
    </el-card>

    <!-- 初步诊断 -->
    <el-card>
      <div class="font-medium mb-2">初步诊断：</div>
      <div class="whitespace-pre-wrap text-gray-700">
        {{ record.diagnosis }}
      </div>
    </el-card>

    <!-- 检验/检查结果 -->
    <el-card>
      <div class="font-medium mb-2">检验/检查结果：</div>
      <el-table :data="tests" stripe size="small" style="width: 100%">
        <el-table-column prop="operator"   label="检验人员"   />
        <el-table-column prop="deptName"   label="所属科室"   />
        <el-table-column prop="name"       label="项目"       />
        <el-table-column prop="result"     label="结果"       />
        <el-table-column prop="resultTime" label="录入时间"   />
      </el-table>
    </el-card>

    <!-- 最终诊断 -->
    <el-card>
      <el-form label-width="100px">
        <el-form-item label="最终诊断">
          <el-input
              type="textarea"
              v-model="finalDiagnosis"
              rows="4"
              placeholder="请输入最终诊断"
          />
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              @click="saveConfirm"
              :loading="saving"
          >保存确诊</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref, watch } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useCounterStore } from '@/stores/counter'

// 接收来自 PatientList 的患者对象
const props = defineProps({
  patient: { type: Object, default: null }
})

const store = useCounterStore()

// 局部患者信息
const localPatient = reactive({
  id:         null,
  casenumber: '',
  realname:   '',
  sex:        '',
  age:        null
})

// 初步诊断 & 检验结果等状态
const record         = reactive({ diagnosis: '' })
const tests          = ref([])
const finalDiagnosis = ref('')
const loading        = ref(false)
const saving         = ref(false)

// 监听 patient.id 变化并拉取数据
watch(
    () => props.patient && props.patient.id,
    async registId => {
      if (!registId) {
        // 清空
        localPatient.id = null
        record.diagnosis = ''
        tests.value = []
        finalDiagnosis.value = ''
        return
      }

      loading.value = true
      try {
        const { data } = await axios.get(
            '/api/doctor/confirm/patient',
            {
              params:  { registId },
              headers: { 'X-User-Id': store.userId }
            }
        )
        const { register, record: rec, tests: ts } = data

        // 覆盖本地患者信息
        localPatient.id         = register.id
        localPatient.casenumber = register.casenumber
        localPatient.realname   = register.realname
        localPatient.sex        = register.sex
        localPatient.age        = register.age

        // 初步诊断
        record.diagnosis     = rec.diagnosis || ''
        finalDiagnosis.value = record.diagnosis

        // 检验结果：多映射 operator 和 deptName
        tests.value = ts.map(t => ({
          name:       t.name,
          result:     t.result,
          resultTime: t.resulttime,
          operator:   t.operator,   // 检验人员
          deptName:   t.deptName    // 所属科室
        }))

      } catch (err) {
        console.error(err)
        ElMessage.error('加载患者确诊数据失败')
      } finally {
        loading.value = false
      }
    },
    { immediate: true }
)

// 保存最终诊断
async function saveConfirm() {
  if (!finalDiagnosis.value.trim()) {
    ElMessage.warning('请填写最终诊断')
    return
  }
  if (!localPatient.id) {
    ElMessage.error('无效的患者信息')
    return
  }

  saving.value = true
  try {
    await axios.post(
        '/api/doctor/confirm',
        {
          registId:  localPatient.id,
          diagnosis: finalDiagnosis.value
        },
        { headers: { 'X-User-Id': store.userId } }
    )
    ElMessage.success('确诊保存成功')
  } catch (err) {
    console.error(err)
    ElMessage.error('保存确诊失败')
  } finally {
    saving.value = false
  }
}
</script>

<style scoped>
.diagnosis-confirm {
  background: #fff;
}
</style>
